/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Paul
 */
public class ServletTest1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * Envoi de données par GET
         */
        try {
            //Contruction de la connexion à la Servlet
            URLConnection conn = constructConnexion();
            String data = "dataTest";
            //Construction de la requête à envoyer
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
            osw.write(data);
            osw.flush();
            osw.close();
            PrintWriter a = response.getWriter();
            a.println("La servlet2 traite la requete");
            InputStream inputStream = conn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = bufferedReader.readLine();
            while (line != null) {
                PrintWriter pw = response.getWriter();
                pw.println("reponse : " +line);
                line = bufferedReader.readLine();
            }
            bufferedReader.close();
            inputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(ServletTest1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private URLConnection constructConnexion() throws IOException, MalformedURLException {
        URL url;
        url = new URL("http://172.30.42.97:8080/WebApplication_GestionNotes/ServletTest2");
        //url = new URL("http://localhost:8080/WebApplication_GestionNotes/ServletTest2");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        return conn;
    }
}
